﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ZDSoft.QLMS.Component.SystemSettingComponent;
using ZDSoft.QLMS.Entity.SystemSetting;
using NHibernate.Criterion;
using ZDSoft.QLMS.Web.Helpers;
using ZDSoft.QLMS.Entity;
using ZDSoft.QLMS.Component;

namespace ZDSoft.QLMS.Web.Controllers
{
    public class UserController : ControllerBase
    {
        UserComponent userComponent = new UserComponent();

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Create()
        {
            return View();
        }

        [HttpPost]
        public void Create(string Account, string Password, string IsActive, string selectedIds)
        {
            string[] ids = selectedIds.Split(',');
            IList<string> roleIDs = new List<string>();
            IList<Role> selectedRoles = new List<Role>();
            IList<string> userManager = new List<string>();
            foreach (string i in ids)
            {
                if (i != "undefined" && i != "")
                {
                    string[] tmp = i.Split('|');
                    if (tmp.Length == 1 && !roleIDs.Contains(tmp[0].Substring(4)))
                    {
                        roleIDs.Add(tmp[0].Substring(4));
                    }
                    else if (tmp.Length == 2)
                    {
                        userManager.Add(tmp[1].Substring(6));
                    }
                }
            }
            foreach (string i in roleIDs)
            {
                selectedRoles.Add(new RoleComponent().FindByID(int.Parse(i)));
            }
            User user = new User() { Account = Account, Password = Password, IsActive = bool.Parse(IsActive), IsReset = false, Roles = selectedRoles };
            user.Create();
            foreach (string i in userManager)
            {
                UserCourse entity = new UserCourse();
                entity.Course = new CourseComponent().FindByID(int.Parse(i));
                entity.User = user;
                entity.Create();
            }
        }

        public ActionResult Update(int id)
        {
            IList<Role> roles = userComponent.FindByID(id).Roles;
            TempData["UserRoles"] = roles;
            return View();
        }

        [HttpPost]
        public void Update(int id, string account, string password, string isActive, string selectedIds)
        {
            User user = userComponent.FindByID(id);
            user.Account = account;
            user.Password = password;
            user.IsActive = bool.Parse(isActive);
            user.Roles = null;
            user.UserCourses = null;
            user.Roles = new List<Role>();
            string[] ids = selectedIds.Split(',');
            IList<string> roleIDs = new List<string>();
            IList<Role> selectedRoles = new List<Role>();
            IList<string> userManager = new List<string>();
            foreach (string i in ids)
            {
                if (i != "undefined" && i != "")
                {
                    string[] tmp = i.Split('|');
                    if (tmp.Length == 1 && !roleIDs.Contains(tmp[0].Substring(4)))
                    {
                        roleIDs.Add(tmp[0].Substring(4));
                    }
                    else if (tmp.Length == 2)
                    {
                        userManager.Add(tmp[1].Substring(6));
                    }
                }
            }
            foreach (string i in roleIDs)
            {
                selectedRoles.Add(new RoleComponent().FindByID(int.Parse(i)));
            }
            user.Roles = selectedRoles;
            user.Update();

            IList<ICriterion> queryConditions = new List<ICriterion>();
            queryConditions.Add(Expression.Eq("User", userComponent.FindByID(id)));
            IList<UserCourse> userCourses = new UserCourseComponent().Find(queryConditions);
            foreach (UserCourse uc in userCourses)
            {
                uc.Delete();
            }
            foreach (string i in userManager)
            {
                UserCourse entity = new UserCourse();
                entity.Course = new CourseComponent().FindByID(int.Parse(i));
                entity.User = user;
                entity.Create();
            }
            AppHelper.LoginedUser = userComponent.FindByID(AppHelper.LoginedUser.ID);
        }

        [HttpPost]
        public void Withdraw(int id)
        {
            User user = userComponent.FindByID(id);
            if (user.IsActive == true)
            {
                user.IsActive = false;
            }
            else
            {
                user.IsActive = true;
            }
            user.Update();
        }

        public string GetAllRoles(int id, int pid, string name, int level)
        {
            string result = "[";
            IList<Role> roles = new RoleComponent().FindAll();
            IList<Course> courses = new CourseComponent().FindAll();
            foreach (Role role in roles)
            {
                int tmpID = int.Parse(id.ToString() + role.ID.ToString());
                if (role.RoleName == "课程负责人")
                {
                    result += "{\"id\":" + tmpID + ",\"pid\":" + id + ",\"tld\":\"role" + role.ID + "\",\"name\":\"" + role.RoleName
                        + "\",\"icon\":\"../../Scripts/zTree/css/zTreeStyle/img/diy/user.png\",\"children\":[";
                    foreach (Course course in courses)
                    {
                        int subTmpID = int.Parse(tmpID.ToString() + course.ID.ToString());
                        result += "{\"id\":" + subTmpID + ",\"pid\":" + tmpID + ",\"tld\":\"role" + role.ID + "|course" + course.ID + "\",\"name\":\"" + course.Name
                        + "\",\"icon\":\"../../Scripts/zTree/css/zTreeStyle/img/diy/course.png\"},";
                    }
                    result = result.Substring(0, result.Length - 1);
                    result += "]},";
                }
                else
                {
                    result += "{\"id\":" + tmpID + ",\"pid\":" + id + ",\"tld\":\"role" + role.ID + "\",\"name\":\"" + role.RoleName
                        + "\",\"icon\":\"../../Scripts/zTree/css/zTreeStyle/img/diy/user.png\"},";
                }
            }
            result = result.Substring(0, result.Length - 1);
            result += "]";
            return result;
        }

        public string GetAllRolesByID(int id, int pid, string name, int level, int userID)
        {
            User user = userComponent.FindByID(userID);
            IList<Role> userRoles = user.Roles;
            IList<ICriterion> queryConditions = new List<ICriterion>();
            queryConditions.Add(Expression.Eq("User", userComponent.FindByID(userID)));
            IList<UserCourse> userCourses = new UserCourseComponent().Find(queryConditions);
            IList<Role> roles = new RoleComponent().FindAll();
            IList<Course> sysCourses = new CourseComponent().FindAll();
            string result = "[";
            foreach (Role sysRole in roles)
            {
                bool flag = false;
                foreach (Role userRole in userRoles)
                {
                    if (sysRole.ID == userRole.ID)
                    {
                        int tmpID = int.Parse(id.ToString() + userRole.ID.ToString());
                        if (userRole.RoleName == "课程负责人")
                        {
                            result += "{\"id\":" + tmpID + ",\"pid\":" + id + ",\"tld\":\"role" + userRole.ID + "\",\"name\":\"" + userRole.RoleName
                            + "\",\"checked\":\"true\",\"icon\":\"../../Scripts/zTree/css/zTreeStyle/img/diy/user.png\",\"children\":[";
                            foreach (Course sysCourse in sysCourses)
                            {
                                bool dFlag = false;
                                int subTmpID = int.Parse(tmpID.ToString() + sysCourse.ID.ToString());
                                foreach (UserCourse userCourse in userCourses)
                                {
                                    if (userCourse.Course.ID == sysCourse.ID)
                                    {
                                        result += "{\"id\":" + subTmpID + ",\"pid\":" + tmpID + ",\"tld\":\"role" + userRole.ID + "|course" + userCourse.Course.ID + "\",\"name\":\"" + userCourse.Course.Name
                                             + "\",\"checked\":\"true\",\"icon\":\"../../Scripts/zTree/css/zTreeStyle/img/diy/course.png\"},";
                                        dFlag = true;
                                        break;
                                    }
                                }
                                if (dFlag == false)
                                {
                                    result += "{\"id\":" + subTmpID + ",\"pid\":" + tmpID + ",\"tld\":\"role" + userRole.ID + "|course" + sysCourse.ID + "\",\"name\":\"" + sysCourse.Name
                                             + "\",\"icon\":\"../../Scripts/zTree/css/zTreeStyle/img/diy/course.png\"},";
                                }
                            }
                            result = result.Substring(0, result.Length - 1);
                            result += "]},";
                        }
                        else
                        {
                            result += "{\"id\":" + tmpID + ",\"pid\":" + id + ",\"tld\":\"role" + userRole.ID + "\",\"name\":\"" + userRole.RoleName
                                + "\",\"checked\":\"true\",\"icon\":\"../../Scripts/zTree/css/zTreeStyle/img/diy/user.png\"},";
                        }
                        flag = true;
                        break;
                    }
                }
                if (flag == false)
                {
                    int tmpID = int.Parse(id.ToString() + sysRole.ID.ToString());
                    if (sysRole.RoleName == "课程负责人")
                    {
                        result += "{\"id\":" + tmpID + ",\"pid\":" + id + ",\"tld\":\"role" + sysRole.ID + "\",\"name\":\"" + sysRole.RoleName
                        + "\",\"icon\":\"../../Scripts/zTree/css/zTreeStyle/img/diy/user.png\",\"children\":[";
                        foreach (Course sysCourse in sysCourses)
                        {
                            int subTmpID = int.Parse(tmpID.ToString() + sysCourse.ID.ToString());
                            result += "{\"id\":" + subTmpID + ",\"pid\":" + tmpID + ",\"tld\":\"role" + sysRole.ID + "|course" + sysCourse.ID + "\",\"name\":\"" + sysCourse.Name
                                        + "\",\"icon\":\"../../Scripts/zTree/css/zTreeStyle/img/diy/course.png\"},";
                        }
                        result = result.Substring(0, result.Length - 1);
                        result += "]},";
                    }
                    else
                    {
                        result += "{\"id\":" + tmpID + ",\"pid\":" + id + ",\"tld\":\"role" + sysRole.ID + "\",\"name\":\"" + sysRole.RoleName
                                + "\",\"icon\":\"../../Scripts/zTree/css/zTreeStyle/img/diy/user.png\"},";
                    }
                }
            }
            result = result.Substring(0, result.Length - 1);
            result += "]";
            return result;
        }

        public string GetUserByID(int id)
        {
            User user = userComponent.FindByID(id);
            IList<KeyValuePair<string, InvokeMethod>> list = new List<KeyValuePair<string, InvokeMethod>>();
            //list.Add(new KeyValuePair<string, InvokeMethod>("xx", GetUsers));
            string str = user.ToJsonString<User>(list);
            return str;
        }

        public JsonResult GetPaged(int pageIndex, int pageSize, string strSearchProperty,
            string strSearchCondition, string strSortProperty, string strSortCondition)
        {
            IList<ICriterion> queryConditions = new List<ICriterion>();
            IList<Order> orderList = new List<Order>();
            if (strSearchProperty != "")
            {
                string[] searchProperties = strSearchProperty.Split(',');
                string[] searchConditions = strSearchCondition.Split(',');
                queryConditions = new List<ICriterion>();
                for (int i = 0; i < searchProperties.Length; i++)
                {
                    queryConditions.Add(Expression.Eq(searchProperties[i], searchConditions[i]));
                }
            }
            if (strSortProperty != "")
            {
                string[] sortProperties = strSortProperty.Split(',');
                string[] sortConditions = strSortCondition.Split(',');
                orderList = new List<Order>();
                for (int i = 0; i < sortProperties.Length; i++)
                {
                    if (sortConditions[i] == "asc")
                    {
                        orderList.Add(new Order(sortProperties[i], true));
                    }
                    else
                    {
                        orderList.Add(new Order(sortProperties[i], false));
                    }
                }
            }

            int count;
            int pageNum;

            IList<User> list = new List<User>();
            IList<User> users = userComponent.GetPaged(queryConditions, orderList, pageIndex, pageSize, out count);

            int tmpcountI = count / pageSize;
            float temCountF = float.Parse(count.ToString()) / float.Parse(pageSize.ToString());
            if (temCountF > float.Parse(tmpcountI.ToString()))
            {
                pageNum = tmpcountI + 1;
            }
            else
            {
                pageNum = tmpcountI;
            }

            foreach (User user in users)
            {
                user.ToJaonResult<User>();
                list.Add(user);
            }
            list.Add(new User() { ID = pageNum });
            JsonResult result = this.Json(list, JsonRequestBehavior.AllowGet);
            return result;
        }
    }
}